#include <stdio.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_log.h"
#include "esp_random.h"

#include "task_two.h"
#include "xlx_platform.h"

#define TASK_TWO_STACK_SIZE (3*512)

static const char* TAG = "task2";
static const char* THIS_H_FILE_NAME = "task two";

TaskHandle_t task_two_handle;
QueueHandle_t task2_send_queue;

/*
 * 创建一个线程，每3秒发生一个数据包到消息队列
 QueueHandle_t
*/

static void show_task_two_file_info(void)
{
    TUTU_LOGI(TAG, "%s\r\n",THIS_H_FILE_NAME);
}

/*
 * 线程回调
*/
static void task_one_cb(void *parameters){
    static unsigned int q_msg_id = 0;

    TUTU_LOGI(TAG, "task_id=%d\r\n", *((int *)parameters));
    TUTU_LOGI(TAG, "task2 is running...\r\n");

    while(1){       
        TUTU_LOGI(TAG, "*");
        vTaskDelay(5000 / portTICK_PERIOD_MS); 
        if (task2_send_queue == NULL) {
            continue;
        }
        
        // 发生一个随机大小到数据包
        task2_queue_msg_t msg;
        unsigned int buff_size = esp_random();
        char * queue_buff;
        buff_size %= 32;
        buff_size += 1;

        TUTU_LOGI(TAG, "buff_size=%d", buff_size);
        queue_buff = malloc(buff_size);

        msg.msg_id = q_msg_id;
        msg.msg_len = buff_size;
        msg.msg_buff = queue_buff;
        memset(msg.msg_buff, 0x30+(buff_size%10), buff_size);
        msg.msg_buff[buff_size-1]= 0x00;

        if(queue_buff == NULL){
            TUTU_LOGE(TAG, "malloc ERROR!");
            continue;
        }else {
            TUTU_LOGW(TAG, "Queue malloc OK(%d@%p), msg_id=%d!",buff_size, queue_buff,q_msg_id);
        }

        xQueueSend(task2_send_queue, (void *)&msg, (TickType_t)2);
        q_msg_id++;
    }

    vTaskDelete(task_two_handle);
}

const int task2_id = 102;
void task_two_init(void){
    int ret = 0;
    TUTU_LOGI(TAG, "-> %s(%s %s) ", __FUNCTION__, __DATE__, __TIME__);
    show_task_two_file_info();

    ret = xTaskCreate(task_one_cb, "task2", TASK_TWO_STACK_SIZE,
                    (void *)&task2_id, 6, &task_two_handle);
    
    if (ret != pdTRUE) {
        TUTU_LOGE(TAG, "%s(ret=%d)\r\n", "task2 create fail!", ret);        

    }
    else {
         TUTU_LOGI(TAG, "%s(ret=%d)\r\n", "task2 create OK", ret);
    }

    if (task2_send_queue == NULL) {
        task2_send_queue = xQueueCreate(10, sizeof(task2_queue_msg_t));
    }    
}